import functools
def log(func):
    def wrapper(*args,**kw):
        print('call: %s function' %(func.__name__))
        return func(*args,**kw)
    return wrapper

def log2(func):
    print('call: %s function' %(func.__name__))

def time(func):
    def warpper(*args,**kw):
        print("call: %s" % (func.__name__))
        return func(*args,**kw)
    return warpper

# 自带参数的decorator
def log3(*text):
    def decorator(func):
        @functools.wraps(func) #防止改变被签名函数的__name__
        def warpper(*args,**kw):
            if not text:
                print("%s():" % (func.__name__))
            else:
                print("%s %s():" % (text,func.__name__))
            return func(*args,**kw)
        return warpper
    return decorator

# log是个decorator，相当于log(xixi)
@log3("helo wor ")
def xixi():
    print("xixi")

@log3("aaaaaaaaaaaa")
def helloworld():
    print("hello world")

xixi()
helloworld()

print(xixi.__name__) # 第20行添加之前是warpper



print("=============================================================================")

import time, functools

# 计算一个函数的执行时间
def metric(fn):
    @functools.wraps(fn)
    def wrapper(*args,**kw):
        print("begin call!")
        start = time.time()
        func = fn(*args,**kw)
        end = time.time()
        print('%s executed in %.8f ms' % (fn.__name__, (end-start)*1000))
        print("end call!")
        return func #返回执行结果。
    return wrapper

# 测试
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')







